package com.hl.card.modular.pack.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.hl.card.common.persistence.model.DistinguishIdCard;
import com.hl.card.common.util.DateUtils;
import com.hl.card.common.util.HttpUtils;
import com.hl.card.config.properties.OSSClientUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import sun.misc.BASE64Decoder;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.apache.commons.codec.binary.Base64.encodeBase64;

/**
 * 图像识别接口
 * 
 * @author 袁伟
 *
 */
@RequestMapping("/api/distinguish")
@RestController
public class DistinguishController {
	@Autowired
	private MongoTemplate mongoTemplate;
	private static String COLLECTION_NAME = "IdCardInfo";
	@Autowired
	private OSSClientUtil oSSClientUtil;
	/*
	 * 获取参数的json对象
	 */
	public static JSONObject getParam(int type, String dataValue) {
		JSONObject obj = new JSONObject();
		try {
			obj.put("dataType", type);
			obj.put("dataValue", dataValue);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return obj;
	}

	@RequestMapping("/save")
	public Map<String, Object> save(String user_id,String phone) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isEmpty(user_id)) {
			result.put("message", "用户ID不能为空");
			result.put("flag", "0");
			return result;
		}
		if (StringUtils.isEmpty(phone)) {
			result.put("message", "手机号码不能为空");
			result.put("flag", "0");
			return result;
		}
		Query query = Query.query(Criteria.where("user_id").is(user_id));
		DistinguishIdCard card=mongoTemplate.findOne(query, DistinguishIdCard.class,COLLECTION_NAME);
		if(card==null||card.getNum()==null||card.getIssue()==null||card.getEnd_date()==null)
		{
			result.put("message", "身份证信息不完整");
			result.put("flag", "0");
			return result;
		}
		Update update=new Update();
		update.set("auth", "2");
		update.set("phone", phone);
		update.set("add_time", DateUtils.getNow("yyyy-MM-dd HH:mm:ss"));
		mongoTemplate.upsert(query, update,COLLECTION_NAME);
		result.put("message", "操作成功");
		result.put("flag", "1");
		return result;
		
	}

	@RequestMapping("/getUserInfo")
	public Map<String, Object> getUserInfo(String user_id) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isEmpty(user_id)) {
			result.put("message", "用户ID不能为空");
			result.put("flag", "0");
			return result;
		}
		Query query = Query.query(Criteria.where("user_id").is(user_id));
		DistinguishIdCard card = mongoTemplate.findOne(query,DistinguishIdCard.class, COLLECTION_NAME);
		if (card == null || "0".equals(card.getAuth())) {
			result.put("message", "未验证");
			result.put("flag", "0");
			return result;
		} else {
			if ("1".equals(card.getAuth())) {
				result.put("message", "验证通过");
				result.put("flag", "1");
				result.put("data", card);
				return result;
			}else if("2".equals(card.getAuth()))
			{
				result.put("message", "验证中");
				result.put("flag", "2");
				result.put("data", card);
				return result;
			}
			else if("3".equals(card.getAuth()))
			{
				result.put("message", "验证失败");
				result.put("flag", "3");
				result.put("data", card);
				return result;
			}
		}
		return result;
	}
	
	
	@RequestMapping("/validate")
	public Map<String, Object> validate(String user_id) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isEmpty(user_id)) {
			result.put("message", "用户ID不能为空");
			result.put("flag", "0");
			return result;
		}
		Query query = Query.query(Criteria.where("user_id").is(user_id));
		DistinguishIdCard card = mongoTemplate.findOne(query,
				DistinguishIdCard.class, COLLECTION_NAME);
		if (card == null || "0".equals(card.getAuth())) {
			result.put("message", "未验证");
			result.put("flag", "0");
			return result;
		} else {
			if ("1".equals(card.getAuth())) {
				result.put("message", "验证通过");
				result.put("flag", "1");
				return result;
			}else if("2".equals(card.getAuth()))
			{
				result.put("message", "验证中");
				result.put("flag", "2");
				return result;
			}
			else if("3".equals(card.getAuth()))
			{
				result.put("message", "验证失败");
				result.put("flag", "3");
				result.put("data", card);
				return result;
			}
		}
		return result;
	}
	@RequestMapping("/distinguishPhoto")
	public Map<String, Object> distinguishPhoto(String img, String type,
			String user_id,String suffix) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isEmpty(user_id)) {
			result.put("message", "用户ID不能为空");
			result.put("flag", "0");
			return result;
		}
		if (StringUtils.isEmpty(type)) {
			result.put("message", "标识不能为空");
			result.put("flag", "0");
			return result;
		}
		if (StringUtils.isEmpty(img)) {
			result.put("message", "图片不能为空");
			result.put("flag", "0");
			return result;
		}
		if (StringUtils.isEmpty(suffix)) {
			result.put("message", "图片后缀不能为空");
			result.put("flag", "0");
			return result;
		}
		img = img.replaceAll(
				"^data:image/(png|gif|jpg|jpeg|bmp|tif|psd|ICO);base64,", "");
		String host = "http://dm-51.data.aliyun.com";
		String path = "/rest/160601/ocr/ocr_idcard.json";
		String appcode = "c0985070c2254fbabf5887ea089b32a9";
		Boolean is_old_format = false;// 如果文档的输入中含有inputs字段，设置为True， 否则设置为False
		// 请根据线上文档修改configure字段
		JSONObject configObj = new JSONObject();
		configObj.put("side", type); // 身份证正反面类型:face/back
		String config_str = configObj.toString();
		// configObj.put("min_size", 5);
		// String config_str = "";

		String method = "POST";
		Map<String, String> headers = new HashMap<String, String>();
		// 最后在header中的格式(中间是英文空格)为Authorization:APPCODE
		// 83359fd73fe94948385f570e3c139105
		headers.put("Authorization", "APPCODE " + appcode);

		Map<String, String> querys = new HashMap<String, String>();

		// 拼装请求body的json字符串
		JSONObject requestObj = new JSONObject();
		try {
			if (is_old_format) {
				JSONObject obj = new JSONObject();
				obj.put("image", getParam(50, img));
				if (config_str.length() > 0) {
					obj.put("configure", getParam(50, config_str));
				}
				JSONArray inputArray = new JSONArray();
				inputArray.add(obj);
				requestObj.put("inputs", inputArray);
			} else {
				requestObj.put("image", img);
				if (config_str.length() > 0) {
					requestObj.put("configure", config_str);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		String bodys = requestObj.toString();

		/**
		 * 重要提示如下: HttpUtils请从
		 * https://github.com/aliyun/api-gateway-demo-sign-java
		 * /blob/master/src/main
		 * /java/com/aliyun/api/gateway/demo/util/HttpUtils.java 下载
		 *
		 * 相应的依赖请参照
		 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master
		 * /pom.xml
		 */
		HttpResponse response = HttpUtils.doPost(host, path, method, headers,
				querys, bodys);
		int stat = response.getStatusLine().getStatusCode();
		if (stat != 200) {
			System.out.println("Http code: " + stat);
			System.out.println("http header error msg: "
					+ response.getFirstHeader("X-Ca-Error-Message"));
			System.out.println("Http body error msg:"
					+ EntityUtils.toString(response.getEntity()));
			result.put("message", EntityUtils.toString(response.getEntity()));
			result.put("flag", "0");
			return result;
		}

		String res = EntityUtils.toString(response.getEntity());
		JSONObject res_obj = JSON.parseObject(res);
		if (is_old_format) {
			if (!res_obj.getBooleanValue("success")) {
				result.put("message", "识别身份证信息失败");
				result.put("flag", "0");
				result.put("data", null);
				return result;
			}
			JSONArray outputArray = res_obj.getJSONArray("outputs");
			String output = outputArray.getJSONObject(0)
					.getJSONObject("outputValue").getString("dataValue");
			JSONObject out = JSON.parseObject(output);
			result.put("message", "操作成功");
			result.put("flag", "1");
			result.put("data", out);
			System.out.println(out.toJSONString());

		} else {
			if (!res_obj.getBooleanValue("success")) {
				result.put("message", "识别身份证信息失败");
				result.put("flag", "0");
				result.put("data", null);
				return result;
			}
			if (type.equals("back")) // 如果是背面验证过期
			{
				if(!"长期".equals(res_obj.getString("end_date")))
				{
					int day = DateUtils.getDateDaysBetween(DateUtils.getNow(),res_obj.getDate("end_date"));
					if (day < 0) {
						result.put("message", "身份证信息过期");
						result.put("flag", "0");
						result.put("data", null);
						return result;
					}
				}
				
				Query query = Query
						.query(Criteria.where("user_id").is(user_id));
				Update update = new Update();
				update.set("start_date", res_obj.getString("start_date"));
				update.set("end_date", res_obj.getString("end_date"));
				update.set("issue", res_obj.getString("issue"));
				update.set("user_id", user_id);
				update.set("auth", "0");
				byte[] s = getInputStream(img);
				String name = oSSClientUtil.uploadImg2Oss(s, suffix);
				String imgUrl = oSSClientUtil.getImgUrl(name);
				update.set("back_img", imgUrl);
				mongoTemplate.upsert(query, update, COLLECTION_NAME);

			} else {
				Query seach_query = Query.query(Criteria.where("num").is(res_obj.getString("num")).and("auth").is("1"));
				DistinguishIdCard c=mongoTemplate.findOne(seach_query, DistinguishIdCard.class,COLLECTION_NAME);
				if(c!=null)
				{
					result.put("message", "身份证信息已绑定其他用户");
					result.put("flag", "0");
					result.put("data", null);
					return result;
				}
				Query query = Query
						.query(Criteria.where("user_id").is(user_id));
				Update update = new Update();
				update.set("address", res_obj.getString("address"));
				update.set("nationality", res_obj.getString("nationality"));
				update.set("num", res_obj.getString("num"));
				update.set("sex", res_obj.getString("sex"));
				update.set("name", res_obj.getString("name"));
				update.set("birth", res_obj.getString("birth"));
				update.set("user_id", user_id);
				update.set("auth", "0");
				byte[] s = getInputStream(img);
				String name = oSSClientUtil.uploadImg2Oss(s, suffix);
				String imgUrl = oSSClientUtil.getImgUrl(name);
				update.set("img", imgUrl);
				mongoTemplate.upsert(query, update, COLLECTION_NAME);
			
			}
			result.put("message", "操作成功");
			result.put("flag", "1");
			result.put("data", res_obj);
			System.out.println(res_obj.toJSONString());
		}

		return result;
	}
	
	/**
	 * 解析base64转换为byte[]
	 * 
	 * @param data
	 * @return
	 * @throws IOException
	 */
	public byte[] getInputStream(String data) throws IOException {
		// 通过base64来转化图片
		BASE64Decoder decoder = new BASE64Decoder();
		// Base64解码
		byte[] imageByte = null;
		try {
			imageByte = decoder.decodeBuffer(data);
			for (int i = 0; i < imageByte.length; ++i) {
				if (imageByte[i] < 0) {// 调整异常数据
					imageByte[i] += 256;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return imageByte;
	}
}